﻿using System;
using System.Net;
using System.Net.Sockets;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Autodesk.AutoCAD.Runtime;
using Autodesk.AutoCAD.ApplicationServices;
using Autodesk.AutoCAD.DatabaseServices;
using System.Runtime.InteropServices;
using Autodesk.AutoCAD.Interop;
using System.IO;
namespace WlanDesign
{
    public partial class FormStartup : Form
    {
        public static FormStartup f = new FormStartup();
        public static string IniFileName = System.Windows.Forms.Application.StartupPath + "\\Config\\Settings.ini";//存储用户名和密码的文件
        public static string IniFile = System.Windows.Forms.Application.StartupPath + "\\Config";//用于判断是否存在Config文件夹，如不存在，则新建文件夹
        public static string IniSysFileName = "c:\\WlanSys.ini";
        public static bool formNetSetstatus = true;//用于保证只打开一个网络设置窗口
        public static bool formAltPasswordstatus = true;//用于保证只打开一个修改密码窗口
        //m代表要加密的密码的起始位号，n代表的是从结尾向前数，不需要加密的位数，m+n要小于输入密码的长度
        public static int m = 3;
        public static int n = 2;
        public FormStartup()
        {
            InitializeComponent();
            Control.CheckForIllegalCrossThreadCalls = false;
        }

        public static string ReadIniTxt(string sPath, string Section, string Key)
        {
            string ServerName;
            IniFileRW ini = new IniFileRW(sPath);
            ServerName = ini.IniReadValue(Section, Key);
            string strSql = ServerName;
            return strSql;
        }
        public static  void WriteIniTxt(string sPath, string Section, string Key, string value)
        {
            string ServerName = value;
            IniFileRW ini = new IniFileRW(sPath);
            ini.IniWriteValue(Section, Key, ServerName);
        }

        public void acAppComObj_BeginQuit(ref bool Cancel)
        {
            labLoginState.Text = "";
            btnAltPass.Visible = false;
            btnNetSet.Visible = false;
            btnDataDown.Visible = false;
            label3.Visible = false;
            panel1.Visible = false;
            label1.Visible = true;
            label2.Visible = true;
            txtUserName.Visible = true;
            txtUserPassword.Visible = true;
            btnLogin.Visible = true;
            chBoxV.Visible = true;
        }
        private void btnLogin_Click(object sender, EventArgs e)
        {
            bool bol = false;//判断是否登录成功的bool变量
            string OriUserNames = ReadIniTxt(IniFileName, "login", "username");//读取原ini文件中所有的用户名组成的字符串
            string OriUserPasswords = ReadIniTxt(IniFileName, "login", "userpass");//读取原ini文件中所有的用户密码组成的字符串
            string UserName = txtUserName.Text.Trim();//输入的用户名（去掉空格）
            string UserPassword=txtUserPassword.Text.Trim();
            if (labLoginState.Text.Contains("欢迎您"))
            {
                MessageBox.Show("已有用户登录，请退出当前用户再登录！");
                return;
            }
            if (UserName == "")
            {
                MessageBox.Show("用户名不能为空，请输入用户名！");
                return;
            }
            if (UserPassword == "")
            {
                MessageBox.Show("密码不能为空，请输入密码！");
                return;
            }
            if (UserPassword.Length < 6)
            {
                MessageBox.Show("密码不能低于6位，请重新输入密码！");
                return;
            }
            if (chBoxV.Checked == true)
            {
                HttpWebResponse Response;
                HttpWebRequest Request;
                Request = (HttpWebRequest)HttpWebRequest.Create("http://192.168.1.106:8080/LogIn?username=" + UserName + "&password=" + UserPassword);
                Request.Headers.Add("Translate: f");
                Request.Credentials = CredentialCache.DefaultCredentials;
                try
                {
                    Response = (HttpWebResponse)Request.GetResponse();
                    Stream respStream = null;
                    respStream = Response.GetResponseStream();
                    Encoding encode = System.Text.Encoding.GetEncoding("utf-8");
                    StreamReader readStream = new StreamReader(respStream, encode);
                    Char[] read = new Char[256];
                    // Reads 256 characters at a time.    
                    int count = readStream.Read(read, 0, 256);
                    String str = "";
                    while (count > 0)
                    {
                        // Dumps the 256 characters on a string and displays the string to the console.
                        str = new String(read, 0, count);
                        count = readStream.Read(read, 0, 256);
                    }
                    Response.Close();
                    readStream.Close();
                    if (str == "true")
                    {
                        UserPassword = security.MD5Encrypt(UserPassword, m, n);//输入的用户密码（去掉空格）注意，后面两个数字要与登录的加密程序一致
                        //判断文件是否存在
                        if (!Directory.Exists(@IniFile))
                        {
                            Directory.CreateDirectory(IniFile);
                            FileStream fs = new FileStream(IniFileName, FileMode.CreateNew);
                            fs.Close();
                        }
                        string[] iniUserNames = OriUserNames.Split(',');//用‘，’将ini文件中提取的用户名字符串分片，提取单个用户名
                        string[] iniUserPassword = OriUserPasswords.Split(',');//用‘，’将ini文件中提取的用户名字符串分片，提取单个用户密码
                        bool isHave = false;
                        //判断用户输入的用户名和用户密码在ini文件中是否存在
                        for (int i = 0; i < iniUserNames.Length; i++)
                        {
                            if (iniUserNames[i] == UserName)
                            {
                                iniUserPassword[i] = UserPassword;
                                isHave = true;
                                break;
                            }
                        }
                        if (isHave == true)
                        {
                            string userNames = iniUserNames[0];
                            string userPasswords = iniUserPassword[0];
                            for (int i = 1; i < iniUserNames.Length; i++)
                            {
                                userNames = userNames + "," + iniUserNames[i];
                                userPasswords = userPasswords + "," + iniUserPassword[i];
                            }
                            FormStartup.WriteIniTxt(FormStartup.IniFileName, "login", "username", userNames);//在ini文件中写入用户名
                            FormStartup.WriteIniTxt(FormStartup.IniFileName, "login", "userpass", userPasswords);//在ini文件中写入用户密码
                        }
                        else
                        {
                            if (OriUserNames == "")
                            {
                                OriUserNames = UserName;
                                OriUserPasswords = UserPassword;
                            }
                            else
                            {
                                OriUserNames = OriUserNames + "," + UserName;
                                OriUserPasswords = OriUserPasswords + "," + UserPassword;
                            }
                            WriteIniTxt(IniFileName, "login", "username", OriUserNames);//在ini文件中写入用户名
                            WriteIniTxt(IniFileName, "login", "userpass", OriUserPasswords);//在ini文件中写入用户密码
                        }
                        MessageBox.Show("恭喜你，登录成功！");
                        labLoginState.Text = "欢迎您" +" "+ UserName;
                        label3.Visible = true;
                        panel1.Visible = true;
                        btnAltPass.Visible = true;
                        btnNetSet.Visible = true;
                        btnDataDown.Visible = true;
                        label1.Visible = false;
                        label2.Visible = false;
                        txtUserName.Visible = false;
                        txtUserPassword.Visible = false;
                        btnLogin.Visible = false;
                        chBoxV.Visible = false;
                        bol = true;
                    }
                }
                catch
                {
                    MessageBox.Show("服务器未打开！");
                    return;
                }
            }
            else
            {
                UserPassword = security.MD5Encrypt(UserPassword, m, n);//输入的用户密码（去掉空格）注意，后面两个数字要与导入的加密程序一致
                string[] iniUserNames = OriUserNames.Split(',');//用‘，’将ini文件中提取的用户名字符串分片，提取单个用户名
                string[] iniUserPassword = OriUserPasswords.Split(',');//用‘，’将ini文件中提取的用户名字符串分片，提取单个用户密码
                //判断用户输入的用户名和用户密码在ini文件中是否存在
                for (int i = 0; i < iniUserNames.Length; i++)
                {
                    if (iniUserNames[i] == UserName && iniUserPassword[i] == UserPassword)
                    {
                        MessageBox.Show("恭喜你，登录成功！");
                        labLoginState.Text = "欢迎您" + " " + UserName;
                        label3.Visible = true;
                        panel1.Visible = true;
                        btnAltPass.Visible = true;
                        btnNetSet.Visible = true;
                        btnDataDown.Visible = true;
                        label1.Visible = false;
                        label2.Visible = false;
                        txtUserName.Visible = false;
                        txtUserPassword.Visible = false;
                        btnLogin.Visible = false;
                        chBoxV.Visible = false;
                        bol = true;
                    }
                }
            }
            //如不存在此用户，或者密码错误，提示相应信息
            if (bol == false)
            {
                MessageBox.Show("用户名或密码不正确，请重新输入！");
            }
            //登录成功，则启动AutoCAD
            else
            {
                AcadApplication acAppComObj = null;
                const string strProgId = "AutoCAD.Application.18";
                // Get a running instance of AutoCAD
                try
                {
                    acAppComObj = (AcadApplication)Marshal.GetActiveObject(strProgId);
                }
                catch // An error occurs if no instance is running
                {
                    try
                    {
                        // Create a new instance of AutoCAD
                        acAppComObj = (AcadApplication)Activator.CreateInstance(Type.GetTypeFromProgID(strProgId), true);
                        
                    }
                    catch
                    {
                        // If an instance of AutoCAD is not created then message and exit
                        System.Windows.Forms.MessageBox.Show("Instance of 'AutoCAD.Application'" +" could not be created.");
                        return;
                    }
                }
                // Display the application and return the name and version
                acAppComObj.Visible = true;
                acAppComObj.WindowState = Autodesk.AutoCAD.Interop.Common.AcWindowState.acMax;
                //System.Windows.Forms.MessageBox.Show("Now running " + acAppComObj.Name + " version " + acAppComObj.Version);
                // Get the active document
                AcadDocument acDocComObj;
                acDocComObj = acAppComObj.ActiveDocument;
                // Optionally, load your assembly and start your command or if your assembly
                // is demandloaded, simply start the command of your in-process assembly.
                //string p = "(command " + (char)34 + "NETLOAD" + (char)34 + " " +(char)34 + System.Environment.CurrentDirectory.Replace('\\', '/') + "/WlanDesignDll.dll" + (char)34 + ") ";
                acDocComObj.SendCommand("(command " + (char)34 + "NETLOAD" + (char)34 + " " +(char)34 + System.Environment.CurrentDirectory.Replace('\\', '/') + "/WlanDesignDll.dll" + (char)34 + ") ");
                //acDocComObj.SendCommand(p);
                acDocComObj.SendCommand("AddMenuCom ");
                acDocComObj.SendCommand("AddApplicationMenuWLAN ");
                label3.Focus();
                //窗口最小化
                this.WindowState = FormWindowState.Minimized;
                acAppComObj.BeginQuit+=new _DAcadApplicationEvents_BeginQuitEventHandler(acAppComObj_BeginQuit);
            }
        }

        private void FormStartup_Load(object sender, EventArgs e)
        {
            skinEngine1.SkinFile = System.Windows.Forms.Application.StartupPath + "\\skin\\MP10.ssk";
        }

        private void FormStartup_FormClosing(object sender, FormClosingEventArgs e)
        {
            AcadApplication acAppComObj = null;
            const string strProgId = "AutoCAD.Application.18";
            try
            {
                acAppComObj = (AcadApplication)Marshal.GetActiveObject(strProgId);
                acAppComObj.Quit();
                if (acAppComObj != null)
                {
                    e.Cancel = true;
                }
            }
            catch
            {
            }
        }

        private void btnAltPass_Click(object sender, EventArgs e)
        {
            if (formAltPasswordstatus)
            {
                FormAltPassword f = new FormAltPassword();
                f.Visible = true;
                formAltPasswordstatus = false;
            }
        }

        private void btnNetSet_Click(object sender, EventArgs e)
        {
            if (formNetSetstatus)
            {
                FormNetSet f = new FormNetSet();
                f.Visible = true;
                formNetSetstatus = false;
            }
        }

        private void btnDataDown_Click(object sender, EventArgs e)
        {
            string fromPath = ReadIniTxt(IniFileName, "network", "svrurl");    //源文件路径
            if (fromPath == "")
            {
                MessageBox.Show("请先进行网络配置！");
                return;
            }
            string downPath = IniSysFileName;                                      //目标路径
            try
            {
                //create web request/response
                HttpWebResponse Response;
                HttpWebRequest Request;
                Request = (HttpWebRequest)HttpWebRequest.Create(fromPath);
                Request.Headers.Add("Translate: f");
                Request.Credentials = CredentialCache.DefaultCredentials;
                Response = (HttpWebResponse)Request.GetResponse();
                Stream respStream = null;
                respStream = Response.GetResponseStream();
                int FileSize = int.Parse(Response.ContentLength.ToString());
                //Do the Download
                byte[] buffer = new byte[FileSize];
                try
                {
                    FileStream fs = File.Open(downPath, FileMode.Create, FileAccess.Write);
                    int length;
                    length = respStream.Read(buffer, 0, FileSize);
                    long writeLength = length;
                    while (length != 0)
                    {
                        fs.Write(buffer, 0, length);
                        length = respStream.Read(buffer, 0, FileSize);
                        writeLength += (long)length;
                    }
                    fs.Close();
                    MessageBox.Show("下载成功！");
                }
                catch
                {
                    MessageBox.Show("下载错误，请选择正确的网址！");
                }
            }
            catch
            {
                MessageBox.Show("请先在网络设置中设置正确的网址！");
                return;
            }
        }
    }
}
